﻿using IService;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Model.AccountDTO;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AlmightyWebAPI.Controllers
{
    [ApiController]
    [EnableCors("any")]
    [Route("[controller]")]
    public class AccontController : Controller
    {
        private readonly IAccountService _accountService;
        public AccontController(IAccountService accountService)
        {
            _accountService = accountService;
        }
        [HttpPost]
        [Route("Register")]
        public bool register(AccountInput userInput)
        {
            return _accountService.register(userInput);
        }
        [HttpPost]
        [Route("Login")]
        public IActionResult Login(AccountOutput userOutput)
        {
            if (_accountService.Login(userOutput)!=true)
            {
                return Ok(false);
            }
            //创建claim
            var authClaims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub,userOutput.UserName),
                new Claim(JwtRegisteredClaimNames.Sub,userOutput.UserPwd),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
            };
            IdentityModelEventSource.ShowPII = true;
            //签名秘钥 可以放到json文件中
            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey"));

            var token = new JwtSecurityToken(
                   issuer: "ZxpToken.Issurer",
                   audience: "ZxpTokendde",
                   expires: DateTime.Now.AddHours(1),
                   claims: authClaims,
                   signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                   );

            HttpContext.Session.SetString("user", authClaims[0].Value);
            //返回token和过期时间
            return Ok(new
            {
                data = true,
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo
            });
            // return _accountService.Login(userOutput);

        }
    }
}
